package com.itheima.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.common.BaseContextUtils;
import com.itheima.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Configuration
@Slf4j
@WebFilter(filterName = "reggin_filter",urlPatterns = "/")
public class RegginWebFilter implements Filter {
    //路径匹配器，支持通配符
    public static final AntPathMatcher pathMatcher = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //强转类型为HttpServletXXX
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        //记录日志
//        log.info("过滤器启动....");
        //获取请求地址
        String requestURI = req.getRequestURI();
        //设置过滤资源
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
//                "/backend/page/common/upload.html",
                "/front/page/login.html",
                "/user/login"
        };
        //判断请求路径
        boolean check = check(requestURI, urls);
        if (check){
            filterChain.doFilter(req,resp);
            return;
        }
        //判断是否登录
        if (req.getSession().getAttribute("employee")!=null){
            log.info("线程{}",Thread.currentThread().getId());
            Long empId =(Long) req.getSession().getAttribute("employee");
            BaseContextUtils.setId(empId);
            filterChain.doFilter(req,resp);
            return;
        }
//        判断是否登录
        if (req.getSession().getAttribute("user")!=null){
            log.info("线程{}",Thread.currentThread().getId());
            Long userId =(Long) req.getSession().getAttribute("user");
            BaseContextUtils.setId(userId);
            log.info("userId="+userId);
            filterChain.doFilter(req,resp);
            return;
        }
        //未登录返回未登录结果，通过输出流向客户端页面响应数据
        ObjectMapper ojm = new ObjectMapper();
        //返回JSON对象
        resp.getWriter().write(ojm.writeValueAsString(R.error("NOTLOGIN")));
    }

    /**
     * 判断请求路径
     * @param requestURI
     * @param urls
     * @return
     */
    public boolean check(String requestURI, String [] urls){
        for (String url :urls){
            if (pathMatcher.match(url,requestURI)){
                return true;
            }
        }
        return false;
    }
}
